import debuger from 'debug';
import { PrismaClient } from '@prisma/client';
import axios from 'axios'

const prisma = new PrismaClient();
const debug = debuger('express:server');

async function refreshToken() {
    const url = 'https://api.atomgit.com/login/oauth/access_token'
    const data = {
        client_id: '6737f74274384078',
        client_secret: '44e25ece24ff496d8e15899d',
        grant_type: 'refresh_token',
        refresh_token: token.refresh_token
    }

    return axios.post(url, data).then(async response => {
        const {
            access_token,
            refresh_token,
        } = response.data

        await prisma.token.create({
            data: {
                token: access_token,
                refresh_token: refresh_token,
                client_id: installation_id,
            }
        });
    }).catch(error => {
        console.error('Error:', error);
    });
}

async function checkDco(payload) {
    const { pull_request: pr, repository, installation, number } = payload
    const signedOffByRegex = /Signed-off-by:\s+(.+)\s+<(.+)>/;
    const match = pr.title.match(signedOffByRegex);
    const url = `https://api.atomgit.com/repos/${repository.owner.name}/${repository.name}/pulls/${number}/comments`;
    let count = 1;
    
    const comments = async (message) => {
        const token = await prisma.token.findFirst({
            where: {
                client_id: String(installation.id)
            },
            orderBy: {
                createdAt: 'desc',
            },
        })
    
        axios.post(url, {
            body: message,
            commit_id: pr.base.hash
        }, {
            headers: {
                Authorization: `Bearer ${token.token}`
            }
        }).then(async res => {
            console.log('Response: ', res.data)

            await prisma.comment.create({
                data: {
                    body: res.data.body,
                    email: repository.owner.email
                }
            })

        }).catch(async error => {
            console.error('Error:', error);
            if(count === 2) return;
            count = count + 1;
            setTimeout(() => {
                count = 1
            }, 30 * 60 * 1000);
            await refreshToken()
            comments();
        });
    }

    if (!match) {
        const message = "无效的Signed-off-by行"
        comments(message);
        return { valid: false, reason: message };
    }

    const [, name, email] = match;
    if (email !== repository.owner.email) {
        const message = "邮箱不匹配"
        comments(message);
        return { valid: false, reason: message };
    }

    return { valid: true };
}

/**
 * @openapi
 * /api/webhook:
 *   post:
 *     tags:
 *     - webhooks
 *     parameters:
 *     description: git hook
 *     responses:
 *       200:
 *         description: hook信息
 */
export const query = async function(req, res, next) {
    try {
        const payload = req.body;
       
        if (!payload || !payload.pull_request || !payload.number) {
            return res.status(400).json({ error: "webhook信息无效" });
        }

        checkDco(payload);

        return res.status(200).send({ data: 'Done' });
    } catch (error) {
        debug(error);
        return res.status(501).send({ 
            message: error.meta?.cause || 'Error!'
        });
    }
}

